//
//  NoTimBuyController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/1.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "NoTimBuyController.h"
#import "NoTimeBuyOneCell.h"
#import "NoTimeBuyTwoCell.h"
#import "NoTimeBuyDetailController.h"
#import "FenLeiDDetailViewController.h"
#import "NoTimeBuyModel.h"


@interface NoTimBuyController ()<UITableViewDelegate, UITableViewDataSource>
{
    int _page;
}
@property (nonatomic, strong)UIButton *rightBtn;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *datarray;
@property (nonatomic, strong)NSMutableArray *datarray222;

@end

@implementation NoTimBuyController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
     self.navigationController.navigationBar.translucent = NO;
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
     self.navigationController.navigationBar.translucent = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 1;
    _datarray = [NSMutableArray array];
    _datarray222 = [NSMutableArray array];
    
    [self configureNaBar];
    [self configureViewController];
    [self getNoTimeBuyDataFromApi];//获取限时秒杀数据
}
- (void)configureNaBar {
    self.navigationItem.title = @"限时秒杀";
    
    //设置导航栏按钮的边距
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [_rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [_rightBtn addTarget:self action:@selector(handleBackAxtion) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    
}
- (void)handleBackAxtion {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


- (void)configureViewController {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height-64) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle =kSpNone;
    [self.view addSubview:_tableView];
    [_tableView registerNib:[UINib nibWithNibName:@"NoTimeBuyOneCell" bundle:nil] forCellReuseIdentifier:@"NoTimeBuyOneCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"NoTimeBuyTwoCell" bundle:nil] forCellReuseIdentifier:@"NoTimeBuyTwoCell"];
    
    
    
    MJRefreshGifHeader *headNew = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestRefresh)];
    NSMutableArray *refreshingImages2 = [NSMutableArray array];
    for (NSUInteger i =1; i<=12; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",i]];
        [refreshingImages2 addObject:image];
    }
    
    NSMutableArray *idleImages2 = [NSMutableArray array];
    for (NSUInteger i =1; i<=12; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",i]];
        [idleImages2 addObject:image];
    }
    // 设置普通状态的动画图片
    [headNew setImages:idleImages2 forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [headNew setImages:refreshingImages2 forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [headNew setImages:refreshingImages2 duration:2 forState:MJRefreshStateRefreshing];
    // 隐藏状态
    headNew.stateLabel.hidden = YES;
    headNew.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = headNew;
    
    
    
    
    
    MJRefreshBackGifFooter *_header = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestDtaLoadMore)];
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSUInteger i =1; i<=12; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",i]];
        [refreshingImages addObject:image];
    }
    
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i =1; i<=12; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",i]];
        [idleImages addObject:image];
    }
    // 设置普通状态的动画图片
    [_header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [_header setImages:refreshingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [_header setImages:refreshingImages duration:2 forState:MJRefreshStateRefreshing];
    // 隐藏状态
    _header.stateLabel.hidden = YES;
    self.tableView.mj_footer = _header;
}

#pragma mark －＝－－＝－＝＝－＝＝－＝－－＝＝－collectionview的刷 新,加载事件
- (void) requestRefresh{
    _page = 1;
    [self getNoTimeBuyDataFromApi];
}
- (void)requestDtaLoadMore {
    _page++;
    [self getNoTimeBuyDataFromApi];
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _datarray.count +1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 150;
    }else {
    return 130;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else {
        return 10;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 10)];
    bgV.backgroundColor = KShouYeBg;
    return bgV;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NoTimeBuyOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoTimeBuyOneCell"];
        cell.selectionStyle = kSeNone;
        return cell;
    }else {
        
        NoTimeBuyModel *model = self.datarray[indexPath.section -1];
        NoTimeBuyTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoTimeBuyTwoCell" forIndexPath:indexPath];
        cell.selectionStyle = kSeNone;
        
        [cell.logoImageV sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:[UIImage imageNamed:@"quetu"]];
        
        cell.tiltLB.text = model.name;
        cell.oneMLB.text = [NSString stringWithFormat:@"¥%@",model.market_price];
        cell.oldMonLB.text = [NSString stringWithFormat:@"¥%@",model.sell_price];
        
        
        
        
        int witrate = 100;
        int count =[model.sales_per intValue];
            UIImageView* imageView = [[UIImageView alloc] initWithFrame:  cell.bgSV.bounds];
            imageView.image = [UIImage imageNamed:@"xianshimiaosha_di"];
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(imageView.frame)/witrate *count, CGRectGetHeight(imageView.frame))];
        
        
            label.backgroundColor = KQiangGour;
        
         UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(imageView.frame), CGRectGetHeight(imageView.frame))];
        label2.backgroundColor = [UIColor clearColor];
        label2.font = kFont13;
        label2.textColor  = [UIColor whiteColor];
        if (count  >= 100) {
            label2.text = @" 已抢光";
        }
        else {
            label2.text = [NSString stringWithFormat:@" 已抢％%d",count];
        }
            [cell.bgSV addSubview:imageView];
            [cell.bgSV addSubview:label];
        [cell.bgSV addSubview:label2];
            
        
        [cell.addCarBtn addTarget:self action:@selector(handleAddbuyCarAction2:) forControlEvents:(UIControlEventTouchUpInside)];
      
        return cell;
        
    }
}
#pragma mark －＝－＝－＝tableView－＝－商品列表添加到添加到购物车
- (void)handleAddbuyCarAction2 :(UIButton *)sender {
    
    NoTimeBuyTwoCell *cell= (NoTimeBuyTwoCell *)[[sender superview] superview];
    NSIndexPath *indaPath = [self.tableView indexPathForCell:cell];
  NoTimeBuyModel *model = self.datarray[indaPath.section-1];
    
    //商品goods_id  sku_id num 为测试数据，应该改为_goodsID ,,,,,
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDicTemp = @{@"userid":saveDic[@"userid"],@"goods_id":[NSString stringWithFormat:@"%@",model.Id],@"sku_id":[NSString stringWithFormat:@"%@",model.sku_id],@"num":[NSString stringWithFormat:@"%@",model.minimum],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    
    [HttpRequest postWithURLString:POST(Shop_CartAddCart) parameters:parameDicTemp success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"加入购物车失败" timeLength:1.5];
            return ;
        }
        
        [MBProgressHUD showText:@"加入购物车成功"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refshIngShopCar" object:nil];
        
        
        [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return;
    }
    else {
        NoTimeBuyModel *model = self.datarray[indexPath.section -1];
        
        FenLeiDDetailViewController *not = [[FenLeiDDetailViewController alloc] init];
        not.goodsID = model.Id;
        [self.navigationController pushViewController:not animated:YES];
    }
    
}


#pragma mark －＝－＝－＝－＝－＝－＝－＝－＝获取限时秒杀数据＝＝＝＝
- (void)getNoTimeBuyDataFromApi {
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"page":[NSString stringWithFormat:@"%d",_page],@"limit":@"20",@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    
    
    [HttpRequest getWithURLString:POST(Shop_GroupbuyGetGroupbuyGoodsList) parameters:parameDic success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (_page ==1) {
            [_datarray removeAllObjects];
        }
        
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"获取限时秒杀商品出错"];
            return ;
        }
        NSDictionary *tempD = responseObject[@"data"];
        
        if (![[NSString stringWithFormat:@"%@",tempD[@"code"]] isEqualToString:@"0"]) {
            [MBProgressHUD showText:tempD[@"msg"]];
            return;
        }
        
        _datarray222 = [NoTimeBuyModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"goodsdata"]];
        
        [_datarray addObjectsFromArray:_datarray222.mutableCopy];
        [self.tableView reloadData];
        
        
        
    } failure:^(NSError *error) {
        
        
        
    }];
    
}









@end
